package com.saxon.controller;

import com.github.pagehelper.PageInfo;
import com.saxon.pojo.Blog;
import com.saxon.service.Blog.BlogServiceImpl;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class BlogController {
    private BlogServiceImpl blogService;

    @Autowired
    public void setBlogService (BlogServiceImpl blogServiceimpl) {
        this.blogService = blogServiceimpl;
    }

    @GetMapping ("/blog/getBlog")
    @ResponseBody
    public List<Blog> getBlog () {
        List<Blog> blogs = blogService.QueryBlog (null);
        return blogs;
    }

    @GetMapping ("/blog/getBlogNew")
    @ResponseBody
    public List<Blog> getBlogNew () {
        return blogService.QueryBlogNew ();
    }

    @GetMapping ("/blog/getBlogBypage")
    @ResponseBody
    public List<Blog> getAllBlogByPage (int pageNum, Integer Tid, Integer id) {
        int pageSize = 5;
        Map<String, Object> map = new HashMap<> ();
        if (Tid != null) {
            map.put ("type_id", Tid);
        }
        PageInfo<Blog> allTypeByPage = blogService.getAllTypeByPage (pageNum, pageSize, map);
        return allTypeByPage.getList ();
    }

    @GetMapping ("/blog/getBlogNum")
    @ResponseBody
    public Map<String, Object> getBlogNum (Integer Tid) {
        Map<String, Object> map = new HashMap<> ();
        if (Tid != null) {
            map.put ("type_id", Tid);
        }
        int totalCount = blogService.QueryBlogNum (map);
        int pageCount = totalCount / 5;
        if (pageCount * 5 <= totalCount) {
            pageCount++;
        }
        HashMap<String, Object> page = new HashMap<> ();
        page.put ("pageCount", pageCount);
        return page;
    }

    @GetMapping ("blog/getBlogById")
    @ResponseBody
    public Blog getBlogById (int pid) {
        Map<String, Object> map = new HashMap<> ();
        map.put ("id", pid);
        List<Blog> blogs = blogService.QueryBlog (map);
        return blogs.get (0);
    }


    //    管理后台代码
    @GetMapping ("/admin/getBlogWithType")
    @ResponseBody
    public List<Blog> queryBlogWithType () {
        return blogService.queryBlogWithType (null);
    }

    @GetMapping ("/admin/blogNum")
    @ResponseBody
    public int queryBlogNum () {
        return blogService.QueryBlogNum (null);
    }

    @Test
    public void test () {
        System.out.println (blogService.QueryBlog (null));
    }
}
